package com.wangsd.system.controller;

import com.gitee.fastmybatis.core.PageInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wangsd.common.controller.AjaxResult;
import com.wangsd.common.controller.BaseController;
import com.wangsd.common.jwt.LoginUser;
import com.wangsd.common.jwt.TokenService;
import com.wangsd.common.utils.ServletUtils;
import com.wangsd.system.entity.Merchant;
import com.wangsd.system.service.MerchantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商户Controller
 *
 * @author wsd
 * @date 2021-06-17
 */
@Api(tags = "商户管理")
@RestController
@RequestMapping("/system/merchant")
public class MerchantController extends BaseController {
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private TokenService tokenService;
    @Value("${wx-appid}")
    private String appId;

    @Value("${wx-auth-notify}")
    private String notify_url;

    @ApiOperation(value = "查询商户列表")
    @GetMapping("/list")
    public AjaxResult<PageInfo<Merchant>> list(Merchant merchant) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        Page page = PageHelper.startPage(ServletUtils.getParameterToInt("pageNum"), ServletUtils.getParameterToInt("pageSize"));
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        list.forEach(item -> {
            String authUrl = "http://121.41.55.48:8777/checkoutCounter/getWxOpenid?wxappid="+appId+"&merchantId="+item.getId();
            item.setAuthUrl(authUrl);
        });
        return AjaxResult.success(getPageInfo(page, list));
    }


    @ApiOperation(value = "获取商户详细信息")
    @GetMapping("/{id}")
    public AjaxResult<Merchant> getInfo(@PathVariable("id") Long id) {
        Merchant merchant = merchantService.selectMerchantById(id);
        return AjaxResult.success(merchant);
    }

    @ApiOperation(value = "新增/修改商户")
    @PostMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody Merchant merchant) {
        if (merchant.getId() == null){
            merchantService.insertMerchant(merchant);
        } else {
            merchantService.updateMerchant(merchant);
        }
        return AjaxResult.success("success");
    }


    @ApiOperation(value = "删除商户")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        merchantService.deleteMerchantById(id);
        return AjaxResult.success("success");
    }
}
